package ztcp_server

import (
	"errors"
	"fmt"
	"net"
)

// Listen 开始监听连接请求
func (c *TcpServer) Listen(port int) (result bool, err error) {
	if c.listen, err = net.Listen("tcp", fmt.Sprintf(":%d", port)); err == nil {
		result = true
		c.init()
		go c.accept()
	}
	return
}

// WriteByIndex 发送数据给指定的索引号
func (c *TcpServer) WriteByIndex(buff []byte, clientIndex int, offset, size int) (count int, err error) {
	if len(buff) < offset+size {
		return 0, errors.New("buffer cache is too small")
	}
	if c.clientList[clientIndex].Conn == nil {
		return 0, errors.New("connect is invalid ")
	}

	if count, err = c.clientList[clientIndex].Conn.Write(buff[offset:size]); err != nil {
		_ = c.close(clientIndex)
	}
	return
}

// WriteBySn 发送数据给指定的设备号
func (c *TcpServer) WriteBySn(buff []byte, sn string, offset, size int) (count int, err error) {
	defer func() {
		if e := recover(); e != nil {
			fmt.Println(e)
		}
	}()

	conn, ok := c.connMap.Load(sn)
	if !ok || conn == nil {
		err = errors.New("device is offline or not register")
		return
	}
	var socketIndex int
	if socketIndex, ok = conn.(int); !ok {
		err = errors.New("device is offline or not register")
		return
	}
	count, err = c.WriteByIndex(buff, socketIndex, offset, size)
	//con := conn.(*net.Conn)
	//count, err = (*con).Write(buff[offset:size])
	if err != nil {
		_ = c.close(socketIndex)
		return
	}

	if count < size {
		_ = c.close(socketIndex)
		err = errors.New("the actual number of data sent is the specified number")
	}

	return
}

// WriteByAddr 发送数据给指定的设备地址(ip+port 组成的地址 例：127.0.0.1:9000)
func (c *TcpServer) WriteByAddr(buff []byte, addr string, offset, size int) (count int, err error) {
	result := false
	for i := 0; i < c.maxConn; i++ {
		if c.clientList[i].Addr == addr && c.clientList[i].Conn != nil {
			result = true
			if count, err = c.WriteByIndex(buff, c.clientList[i].Index, offset, size); err == nil {
				break
			}
		}
	}
	if !result {
		err = errors.New("addr not exist")
	}
	return
}

// CloseAll 关闭所有客户端连接
func (c *TcpServer) CloseAll() {
	for i := 0; i < c.maxConn; i++ {
		if c.clientList[i].Conn != nil {
			_ = c.close(c.clientList[i].Index)
		}
	}
}

// ===================================================================================================================

// GetConnectCount 获取当前连接总数
func (c *TcpServer) GetConnectCount() (count int) {
	count = c.connSum
	return
}

// GetConnectInfo 获取所有的连接信息
func (c *TcpServer) GetConnectInfo() (clients []TcpClient) {
	for i := 0; i < c.maxConn; i++ {
		if c.clientList[i].Conn != nil {
			clients = append(clients, c.clientList[i])
		}
	}
	return
}

// GetConnectTimeout 获取连接无数据超时时长()
func (c *TcpServer) GetConnectTimeout() int64 {
	return c.connTimeout
}

// ===================================================================================================================

// SetConnSn 给tcp客户端的设置SN,以便可以用SN来主动发送数据给客户端
func (c *TcpServer) SetConnSn(sn string, index int) {
	if index < 0 {
		return
	}
	c.clientList[index].Sn = sn
	c.connMap.Store(sn, index)
}

// SetCheckConn 开启或关闭连接超时检测
func (c *TcpServer) SetCheckConn(v bool) {
	c.checkConn = v
}

// SetCheckInterval 设置连检测间隔
func (c *TcpServer) SetCheckInterval(interval int) {
	c.checkInterval = interval
}

func (c *TcpServer) SetConnectTimeout(timeout int64) {
	c.connTimeout = timeout
}

// SetDataCallback 设置接收数据回调函数
func (c *TcpServer) SetDataCallback(callback ReceiveEvent) {
	c.dataCallback = callback
}

// SetConnectCallback 设置连接信息回调函数
func (c *TcpServer) SetConnectCallback(callback ConnectEvent) {
	c.connCallback = callback
}

// SetReadErrorEvent 读取错误事件
func (c *TcpServer) SetReadErrorEvent(callback ReadErrorEvent) {
	c.onReadErrorEvent = callback
}

// SetMaxConnect 设置最大连接数量
func (c *TcpServer) SetMaxConnect(size int) {
	c.maxConn = size
}

// SetProtocolFormat 设置协议格式
func (c *TcpServer) SetProtocolFormat(protoFormat ProtocolFormat) {
	c.protoFormat = protoFormat
	c.protoFormat.headLen = len(c.protoFormat.Head)
	c.protoFormat.endLen = len(c.protoFormat.End)
}

// SetJsonDataFormat 设置接收数据为json格式
func (c *TcpServer) SetJsonDataFormat(b bool) {
	c.isJson = b
}
